import inquirer from 'inquirer';
import fs from 'fs-extra';
import path from 'path';
import { fileURLToPath } from 'url';
import { exec, spawn } from 'child_process';
import { promisify } from 'util';

const execAsync = promisify(exec);
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const rootDir = path.join(__dirname, '..');

async function buildProject(projectPath) {
  try {
      const packageJsonPath = path.join(projectPath, 'package.json');
      if (!fs.existsSync(packageJsonPath)) {
          console.log(`项目 ${path.basename(projectPath)} 中未找到 package.json`);
          return false;
      }

      const projectName = path.basename(projectPath);
      console.log(`开始构建项目: ${projectName}`);

      // 执行构建
      const { stdout, stderr } = await execAsync('npm run build', { cwd: projectPath });
      console.log(stdout);
      if (stderr) console.error(stderr);

      // 移动 dist 文件夹
      const distPath = path.join(projectPath, 'dist');
      const outputPath = path.join(rootDir, 'output', projectName);

      if (fs.existsSync(distPath)) {
          // 确保输出目录存在
          await fs.ensureDir(path.join(rootDir, 'output'));

          // 如果目标文件夹已存在，先删除
          if (fs.existsSync(outputPath)) {
              await fs.remove(outputPath);
          }

          // 移动文件夹
          await fs.move(distPath, outputPath);
          console.log(`已将构建文件移动到: ${outputPath}`);
      } else {
          console.log(`警告：未找到构建输出目录 ${distPath}`);
      }

      return true;
  } catch (error) {
      console.error(`构建失败: ${error.message}`);
      return false;
  }
}

async function generateConfig(selectedProjects) {
    const configPath = path.join(rootDir, 'output', 'config.js');
    const staticPaths = [
        {
            path: "/",
            dir: "main"
        },
        ...selectedProjects.map(project => ({
            path: `/${project}`,
            dir: project
        }))
    ];

    const configContent = `export const staticPaths = ${JSON.stringify(staticPaths, null, 2)};`;
    await fs.writeFile(configPath, configContent, 'utf-8');
    console.log('已生成服务器配置文件');
}

async function selectProject() {
    const projectsPath = path.join(rootDir, 'projects');

    // 先选择要执行的命令
    const commandAnswer = await inquirer.prompt([
        {
            type: 'list',
            name: 'command',
            message: '请选择要执行的命令：',
            choices: [
                { name: '构建项目 (build)', value: 'build' },
                { name: '启动服务 (serve)', value: 'serve' }
            ]
        }
    ]);

    const selectedCommand = commandAnswer.command;

    const projects = fs.readdirSync(projectsPath).filter(file => {
        return fs.statSync(path.join(projectsPath, file)).isDirectory();
    });

    if (projects.length === 0) {
        console.log('没有找到任何项目！');
        return;
    }

    // 必须选中的项目
    const defalutSelectedProjects = ['main'];

    const answer = await inquirer.prompt([
        {
            type: 'checkbox',
            name: 'selectedProjects',
            message: `请选择要${selectedCommand === 'build' ? '构建' : '启动'}的项目（空格键选择，回车确认）：`,
            choices: projects.map(project => ({
                name: project,
                value: project,
                checked: selectedCommand === 'serve' ? true : defalutSelectedProjects.includes(project)
            }))
        }
    ]);

    let selectedProjects = answer.selectedProjects;

    if (selectedProjects.length === 0) {
        console.log('未选择任何项目');
        return;
    }

    console.log(`准备${selectedCommand === 'build' ? '构建' : '启动'}以下项目: ${selectedProjects.join(', ')}`);

    if (selectedCommand === 'build') {
        // 执行所有构建任务
        for (const project of selectedProjects) {
            const projectPath = path.join(projectsPath, project);
            await buildProject(projectPath);
        }
        // 生成配置文件
        await generateConfig(selectedProjects);
    } else {
        // 计数器
        let completedCount = 0;
        for (const project of selectedProjects) {
            const projectPath = path.join(projectsPath, project);
            spawn('cmd.exe', ['/c', 'start', 'cmd.exe', '/k', 'npm run serve'], {
                cwd: projectPath,
                windowsHide: false
            });
            completedCount++;
            console.log(`${project}项目正在启动`);
            if (completedCount == selectedProjects.length) {
                console.log('所有项目已启动');
                setTimeout(() => {
                    process.exit(0);
                }, 5000);
            }
        }
    }
}

// 执行选择和构建
selectProject().catch(console.error);
